<?php

namespace App\Admin\Controllers\fund;

use App\Admin\Renderable\AdminGroupTable;
use App\Admin\Renderable\UserTable;
use App\Models\AdminCharityFund;
use App\Models\AdminUserGroup;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;

class CreateController extends AdminController
{
    protected $title = "基金";

    protected $translation = 'admin-charity-fund';

    public function index(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminCharityFund(), function (Form $form) {
            $form->disableListButton();
            $form->action('/fund/step');
            $form->multipleSteps()
                ->remember()
                ->add('基本信息',fn($step) => $this -> firstFrom($step) )
                ->add('选填信息',fn($step) => $this -> secondFrom($step))
                ->add('基金详情', fn($step) => $this -> thirdFrom($step));
        });
    }

    public function firstFrom($form) {
        $form->text('title')
            ->required();

        $form->textarea('description')
            ->required();

        $form->radio('charity_fund_type')
            ->options(fn () => trans('admin-charity-fund.options.charity_fund_type'))
            ->default(0)
            ->required();

        $form->radio('use_type')
            ->options(fn () => trans('admin-charity-fund.options.use_type'))
            ->default(0)
            ->required();

        $form->dateRange('start_time', 'end_time', '筹款时间')
            ->required();

        $map_data = [
            'name'      => 'address',
            'address'   => $form->model()->address,
            'longitude' => $form->model()->longitude,
            'latitude'  => $form->model()->latitude
        ];

        $form->html(view('admin.components.map-dialog', $map_data)->render(),'项目地址')
            ->required();

        $form->number('target_amount', '基金本金')
            ->required();

        $donation_amount_data_3 = [
            'name'          => 'personal_donation_amount_3',
            'default_values' => [20, 50, 100],
            'init_values'    => ['','',''],
            'personal_donation_amount_type' => 0
        ];

        $donation_amount_data_6 = [
            'name'          => 'personal_donation_amount_6',
            'default_values' => [20, 50, 100, 200, 500, 1000],
            'init_values'    => ['','','','','',''],
            'personal_donation_amount_type' => 1
        ];

        $personal_donation_amount_type = 0;

        if($form->model()->personal_donation_amount) {
            $init_personal_values = explode(',', $form->model()->personal_donation_amount);
            if(count($init_personal_values) === 3) {
                $personal_donation_amount_type = 0;
                $donation_amount_data_3['init_values'] = $init_personal_values;
            } else {
                $personal_donation_amount_type = 1;
                $donation_amount_data_6['init_values'] = $init_personal_values;
            }
        }

        $form->radio('personal_donation_amount_type','个人捐款选项')
            ->when(0, function ($form) use ($donation_amount_data_3) {
                $form->html(view('admin.components.donation-amount', $donation_amount_data_3)->render());
            })
            ->when(1, function ($form) use ($donation_amount_data_6) {
                $form->html(view('admin.components.donation-amount', $donation_amount_data_6)->render());
            })
            ->options([
                0 => '三个选项',
                1 => '六个选项'
            ])
            ->value($personal_donation_amount_type)
            ->required();

        $corporate_donation_amount_3 = [
            'name'          => 'corporate_donation_amount_3',
            'default_values' => [20, 50, 100],
            'init_values'    => ['','','']
        ];
        $corporate_donation_amount_6 = [
            'name'          => 'corporate_donation_amount_6',
            'default_values' => [20, 50, 100, 200, 500, 1000],
            'init_values'    => ['','','','','','']
        ];

        $corporate_donation_amount_type = 0;

        if($form->model()->corporate_donation_amount) {
            $init_corporate_values = explode(',', $form->model()->corporate_donation_amount);
            if(count($init_corporate_values) === 3) {
                $corporate_donation_amount_type = 0;
                $corporate_donation_amount_3['init_values'] = $init_corporate_values;
            } else {
                $corporate_donation_amount_type = 1;
                $corporate_donation_amount_6['init_values'] = $init_corporate_values;
            }
        }

        $form->radio('corporate_donation_amount_type','企业捐款选项')
            ->when(0, function ($form) use($corporate_donation_amount_3) {
                $form->html(view('admin.components.donation-amount', $corporate_donation_amount_3)->render());
            })
            ->when(1, function ($form) use($corporate_donation_amount_6) {
                $form->html(view('admin.components.donation-amount', $corporate_donation_amount_6)->render());
            })
            ->options([
                0 => '三个选项',
                1 => '六个选项'
            ])
            ->value($corporate_donation_amount_type)
            ->required();

        $form->text('random_donation_amount')
            ->help('随缘捐选项配置说明：请输入项目捐赠随缘捐选项，用英文逗号隔开，例如：6.6,8.8,10,16.6,20,28.8,36.6,52,88.8,如输入0则关闭随缘捐');

        $form->selectTable('user_id')
            ->from(UserTable::make(['id' => $form->getKey()]))
            ->model(User::class, 'id', 'name')
            ->required();

        $form->selectTable('group_id')
            ->from(AdminGroupTable::make(['id' => $form->getKey()]))
            ->model(AdminUserGroup::class, 'id', 'name')
            ->required();

        $form->image('cover_path')
            ->url('/upload')
            ->uniqueName()
            ->autoUpload()
            ->maxSize(5120)
            ->required();
    }
    public function secondFrom($form)
    {
        $form->text('registration_number');
        $form->text('fund_code');
        $form->table('administrative_committee',function (NestedForm $table) {
            $table->text('position','职务');
            $table->text('name','姓名');
        });
        $form->radio('donation_type') -> options(trans('admin-charity-fund.options.donation_type')) -> default(0);
        $form->switch('online_status');
        $form->switch('donate_together');
    }
    public function thirdFrom($form)
    {
        $form->editor('content')->required();
    }
    public function validateStepForm(Request $request)
    {
        $step = $request->input('CURRENT_VALIDATION_STEP');

        $all = $request->input('ALL_STEPS', 0);

        if($all == 1) {
            return $this->finishStepForm($request);
        }

        switch($step) {
            case 0:
                return $this -> validateFirstStepFrom($request);
            case 1:
                return $this -> validateSecondStepFrom($request);
            case 2:
                return $this -> validateThirdStepFrom($request);
        }
    }
    public function validateFirstStepFrom(Request $request)
    {
        return $request->validate([
            'title'                          => 'required|string|max:100',
            'description'                    => 'required|string|max:200',
            'charity_fund_type'              => 'required',
            'use_type'                       => 'required',
            'start_time'                     => 'required|date_format:Y-m-d',
            'end_time'                       => 'required|date_format:Y-m-d',
            'address'                        => 'required|string',
            'longitude'                      => 'required|numeric|between:-180,180',
            'latitude'                       => 'required|numeric|between:-90,90',
            'target_amount'                  => 'required|numeric|min:0',
            'personal_donation_amount_type'  => 'required|in:0,1',
            'personal_donation_amount_3'     => 'required_if:personal_donation_amount_type,0|array|size:3',
            'personal_donation_amount_6'     => 'required_if:personal_donation_amount_type,1|array|size:6',
            'corporate_donation_amount_type' => 'required|in:0,1',
            'corporate_donation_amount_3'    => 'required_if:corporate_donation_amount_type,0|array|size:3',
            'corporate_donation_amount_6'    => 'required_if:corporate_donation_amount_type,1|array|size:6',
            'random_donation_amount'         => 'nullable|string|max:100',
            'user_id'                        => 'required|exists:users,id',
            'group_id'                       => 'required|exists:admin_user_groups,id',
            'cover_path'                     => 'required',
        ], [
            'title.required'                          => '请输入基金标题',
            'description.required'                    => '请输入基金简介',
            'charity_fund_type.required'              => '请选择基金类型',
            'use_type.required'                       => '基金类型不存在',
            'start_time.required'                     => '请选择基金开始时间',
            'start_time.date_format'                  => '基金开始时间格式错误',
            'end_time.required'                       => '请选择基金结束时间',
            'end_time.date_format'                    => '基金结束时间格式错误',
            'address.required'                        => '请选择基金项目地址',
            'longitude.required'                      => '请输入经度',
            'longitude.between'                       => '经度必须在-180到180之间',
            'latitude.required'                       => '请输入纬度',
            'latitude.between'                        => '纬度必须在-90到90之间',
            'target_amount.required'                  => '请输入基金目标金额',
            'target_amount.min'                       => '目标金额不能为负数',
            'excess_donation.required'                => '请确认是否可以超目标金额捐款',
            'personal_donation_amount_type.required'  => '请选择个人捐款选项',
            'personal_donation_amount_3.required_if'  => '请提供个人捐款金额（3个选项）',
            'personal_donation_amount_3.size'         => '个人捐款金额必须包含3个选项',
            'personal_donation_amount_3.*.numeric'    => '个人捐款金额必须为数字',
            'personal_donation_amount_6.required_if'  => '请提供个人捐款金额（6个选项）',
            'personal_donation_amount_6.size'         => '个人捐款金额必须包含6个选项',
            'personal_donation_amount_6.*.numeric'    => '个人捐款金额必须为数字',
            'corporate_donation_amount_3.required_if' => '请提供企业捐款金额（3个选项）',
            'corporate_donation_amount_3.size'        => '企业捐款金额必须包含3个选项',
            'corporate_donation_amount_3.*.numeric'   => '企业捐款金额必须为数字',
            'corporate_donation_amount_6.required_if' => '请提供企业捐款金额（6个选项）',
            'corporate_donation_amount_6.size'        => '企业捐款金额必须包含6个选项',
            'corporate_donation_amount_6.*.numeric'   => '企业捐款金额必须为数字',
            'corporate_donation_amount_type.required' => '请选择企业捐款选项',
            'random_donation_amount.string'           => '随机捐款金额必须为字符串',
            'user_id.required'                        => '请选择项目负责人',
            'user_id.exists'                          => '项目负责人不存在',
            'group_id.required'                       => '请选择项目所属团队',
            'group_id.exists'                         => '团队不存在',
            'cover_path.required'                     => '请上传封面图片',
        ]);
    }
    public function validateSecondStepFrom(Request $request)
    {

        return $request->validate([
            'registration_number'      => 'nullable|max:100',
            'fund_code'                => 'nullable|max:24',
            'administrative_committee' => 'nullable|array',
            'donation_type'            => 'nullable|in:0,1',
            'online_status'            => 'nullable|in:0,1',
            'donate_together'          => 'nullable|in:0,1',
        ], [
            'registration_number.max'        => '备案号格式错误',
            'fund_code.max'                  => '基金编号格式错误',
            'administrative_committee.array' => '管委会成员格式错误',
            'donation_type.required'         => '请选择捐款模式',
            'online_status.required'         => '请选择上线状态',
            'donate_together.required'       => '请选择是否开启一起捐',
        ]);
    }
    public function validateThirdStepFrom(Request $request)
    {

        return $request->validate([
            'content'     => 'required'
        ], [
            'content.required'   => '请填写具体内容',
        ]);
    }
    public function finishStepForm(Request $request)
    {
        $input = $request -> input();

        $model = new AdminCharityFund();

        $data = $request->only($model->getFillable());

        $data['admin_id'] =  Admin::user()->id;
        $data['random_donation_amount'] = $input['random_donation_amount'] ?? '0';
        $data['personal_donation_amount'] = implode(',', setDonationAmounts($input, 'personal'));
        $data['corporate_donation_amount'] = implode(',', setDonationAmounts($input, 'corporate'));

        if(key_exists('administrative_committee', $data) && $data['administrative_committee']) {
            $filtered = collect($data['administrative_committee'])
                ->filter(fn($item) => empty($item['_remove_']) || $item['_remove_'] == '0')
                ->map(function ($item) {
                    unset($item['_remove_']);
                    return $item;
                })
                ->values();

            $data['administrative_committee'] = json_encode($filtered, JSON_UNESCAPED_UNICODE);
        }

        $model->create($data);

        $data = [
            'title'       => trans('admin.save_succeeded'),
            'description' => '',
            'createUrl'   => '/admin/fund/create',
            'backUrl'     => '/admin/fund/list',
        ];

        return view('dcat-admin.form-step::completion-page', $data);
    }
}
